namespace WP7Contrib.Communications
{
    using System.IO;
    using System.Runtime.Serialization.Json;

    public class JsonContractSerializer : ISerializer
    {
        public string ContentType { get { return "application/json"; } }

        public Stream Serialize(object graph)
        {
            var mem = new MemoryStream();
            if (graph != null)
            {
                var serializer = new DataContractJsonSerializer(graph.GetType());
                serializer.WriteObject(mem, graph);
            }

            mem.Position = 0;
            return mem;
        }

        public T Deserialize<T>(Stream stream) where T : class
        {
            T result = default(T);
            if (stream != null && stream.Length > 0)
            {
                var serializer = new DataContractJsonSerializer(typeof(T));
                stream.Position = 0;
                result = (T)serializer.ReadObject(stream);
            }

            return result;
        }
    }
}
